//
//  XLFileListViewController.m
//  XLConversationInputView
//
//  Created by ilongge on 2022/8/9.
//


NSString *const XLCFileTypeKeyWordDoc             = @"doc";
NSString *const XLCFileTypeKeyWordDocx            = @"docx";
NSString *const XLCFileTypeKeyExcelXls            = @"xls";
NSString *const XLCFileTypeKeyExcelXlsx           = @"xlsx";
NSString *const XLCFileTypeKeyPowerPointPpt       = @"ppt";
NSString *const XLCFileTypeKeyPowerPointPptx      = @"pptx";
NSString *const XLCFileTypeKeyZip                 = @"zip";
NSString *const XLCFileTypeKeyRar                 = @"rar";
NSString *const XLCFileTypeKeyTxt                 = @"txt";
NSString *const XLCFileTypeKeyText                = @"text";
NSString *const XLCFileTypeKeyLog                 = @"log";
NSString *const XLCFileTypeKeyPdf                 = @"pdf";

#import "XLFileListViewCell.h"
#import "XLFileListViewController.h"
#import "XLFileListModel.h"
#import "XLConversationInputViewDef.h"
#import <QuickLook/QuickLook.h>

@interface XLFileListViewController ()
<
UITableViewDelegate,
UITableViewDataSource,
QLPreviewControllerDataSource,
QLPreviewControllerDelegate
>
@property (nonatomic, strong) NSMutableArray *fileModelList;
@property (nonatomic, strong) UITableView *fileListTable;
@property (nonatomic, strong) NSURL *selectFileUrl;
@end

@implementation XLFileListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.layer.backgroundColor = [UIColor colorWithRed:239/255.0 green:239/255.0 blue:239/255.0 alpha:1.0].CGColor;
    [self setNavTitle:@"文件"
       leftButtonItem:[self normalBackButton]
      rightButtonItem:[self customBarItemButton:@"发送" backgroundImage:nil foreground:nil sel:@selector(conformAction)]];
    [self initData];
    [self initView];
}

- (void)conformAction {
    if (self.sendFileBlock) {
        NSMutableArray *fileArray = [[NSMutableArray alloc] init];
        for (XLFileListModel *file in self.fileModelList) {
            if (file.isSelect) {
                [fileArray addObject:file.convertToDictory];
            }
        }
        self.sendFileBlock(fileArray.copy);
    }
    [self leftBackAction];
}

/// 初始化数据
- (void)initData{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *document = [paths firstObject];
    NSString *inbox = [NSString stringWithFormat:@"%@/Inbox", document];
    NSMutableArray *scanDirectoryList = [NSMutableArray array];
    [scanDirectoryList addObject:inbox];
    if (self.delegate && [self.delegate respondsToSelector:@selector(fileListDirectory)]) {
        NSArray *directoryList = [self.delegate fileListDirectory];
        [scanDirectoryList addObjectsFromArray:directoryList];
    }
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSMutableArray *allFileList = [NSMutableArray array];
    
    for (NSString *directory in scanDirectoryList) {
        NSArray *fileList = [fileManager subpathsAtPath:directory];
        for (NSString *filePath in fileList) {
            NSString *fullFilePath = [NSString stringWithFormat:@"%@/%@", directory,filePath];
            [allFileList addObject:fullFilePath];
        }
    }
    
    self.fileModelList = [NSMutableArray array];
    
    NSMutableArray *fileList = [NSMutableArray array];
    for (NSString *item in allFileList) {
        NSDictionary *fileAttr = [fileManager attributesOfItemAtPath:item error:nil];
        NSMutableDictionary *fileAttrDict = [NSMutableDictionary dictionaryWithDictionary:fileAttr];
        fileAttrDict[@"NSFilePath"] = item;
        NSArray *fileNameList = [item componentsSeparatedByString:@"."];
        NSMutableArray *name_array = [NSMutableArray arrayWithArray:fileNameList];
        fileAttrDict[@"NSFileExtension"] = @"";
        if (name_array.count > 1) {
            fileAttrDict[@"NSFileExtension"] = name_array.lastObject;
            [name_array removeLastObject];
        }
        NSString *fileName = [[name_array[0] componentsSeparatedByString:@"/"] lastObject];
        fileAttrDict[@"NSFileName"] = fileName;
        XLFileListModel *model = [[XLFileListModel alloc] initWith:fileAttrDict];
        [fileList addObject:model];
    }
    NSArray *supportExten = nil;
    if (self.delegate || [self.delegate supportFileTypes]){
        supportExten = [self.delegate supportFileTypes];
    }
    if (supportExten.count){
        for (XLFileListModel *model in fileList) {
            if ([supportExten containsObject:model.fileExtension]) {
                [self findFileLogo:model];
                [self.fileModelList addObject:model];
            }
        }
    }
    else{
        NSLog(@"请配置支持的文件类型");
    }
}

- (void)findFileLogo:(XLFileListModel *)fileAttrModel{
    NSString *imageName = nil;
    if ([fileAttrModel.fileExtension isEqualToString:@"xlsx"]
        ||
        [fileAttrModel.fileExtension isEqualToString:@"xls"]) {
        imageName = @"office_excel";
    }
    else if ([fileAttrModel.fileExtension isEqualToString:@"docx"]
             ||
             [fileAttrModel.fileExtension isEqualToString:@"doc"]) {
        imageName = @"office_word";
    }
    else if ([fileAttrModel.fileExtension isEqualToString:@"pptx"]
             ||
             [fileAttrModel.fileExtension isEqualToString:@"ppt"]) {
        imageName = @"office_pptx";
    }
    else if ([fileAttrModel.fileExtension isEqualToString:@"pdf"]) {
        imageName = @"icon_pdf";
    }
    else if ([fileAttrModel.fileExtension isEqualToString:@"txt"]
             ||
             [fileAttrModel.fileExtension isEqualToString:@"text"]
             ||
             [fileAttrModel.fileExtension isEqualToString:@"log"]) {
        imageName = @"icon_txt";
    }
    else if ([fileAttrModel.fileExtension isEqualToString:@"zip"]) {
        imageName = @"icon_pdf";
    }
    
    else if ([fileAttrModel.fileExtension isEqualToString:@"rar"]) {
        imageName = @"icon_zip";
    }
    fileAttrModel.logo = imageName;
}

/// 初始化视图
- (void)initView{
    [self.view addSubview:self.fileListTable];
    [self.fileListTable reloadData];
}

- (void)viewWillLayoutSubviews{
    [super viewWillLayoutSubviews];
    self.fileListTable.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.fileModelList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    XLFileListViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"XLFileListViewCell"];
    if (cell == nil) {
        cell = [[XLFileListViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"XLFileListViewCell"];
    }
    XLFileListModel *model = self.fileModelList[indexPath.row];
    [cell setFileAttrModel:model];
    WeakSelf(weakSelf);
    [cell moreButtonBlock:^{
        StrongSelf(strongSelf);
        [strongSelf openFileWith:model];
    }];
    return cell;
}

- (void)openFileWith:(XLFileListModel *)model {
    QLPreviewController *previewController = [[QLPreviewController alloc] init];
    previewController.dataSource = self;
    self.selectFileUrl = [NSURL fileURLWithPath:model.filePath];
    [self.navigationController pushViewController:previewController animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    XLFileListModel *dict = self.fileModelList[indexPath.row];
    dict.isSelect = !dict.isSelect;
    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}

#pragma mark - QLPreviewControllerDataSource

- (id<QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index {
    return self.selectFileUrl ;
}


- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)previewController{
    
    return 1;
    
}

- (UITableView *)fileListTable {
    if (_fileListTable == nil) {
        _fileListTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStylePlain];
        _fileListTable.delegate = self;
        _fileListTable.dataSource = self;
        _fileListTable.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_fileListTable registerClass:XLFileListViewCell.class forCellReuseIdentifier:@"XLFileListViewCell"];
    }
    return _fileListTable;
}
@end
